import axios from 'axios';
import router from "@/router/router.js";
import {Notification, Loading } from 'element-ui'

axios.defaults.baseURL = process.env.BASE_URL;
axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';

let loadingInstance = null;
let loadingCount = 0;

function openLoading() {
  loadingCount++;
  loadingInstance = Loading.service({});
}

function closeLoading() {
  loadingCount--;
  if(loadingCount < 1 && loadingInstance) {
    loadingInstance.close();
  }
}


axios.interceptors.request.use(
  request => {
    openLoading();
    return request;
  },
  err => {
    return Promise.reject(err)
  }
);

axios.interceptors.response.use(
  response => {
    closeLoading();
    if(response && response.status == 200 && response.data) {
      if(response.data.code == 'OFFLINE') {
          router.push('/user/login');
      } else if (response.data.code == 'ERROR') {
        Notification.error({
          title: '错误',
          message: '出错了'
        });
      } else {
        return response;
      }
    } 
  }
);